package com.xl.bigdata.es.search;

import com.xl.bigdata.es.xpack.ESXpackRestHighLevelClient;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.core.CountRequest;
import org.elasticsearch.client.core.CountResponse;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;

import java.io.IOException;

/**
 * @ClassName CountAPI
 * @Description TODO
 * @Author xl.gao
 * @Date 2022/1/6 9:27
 * @Version
 */
public class CountAPI {

    public static long countAPI(RestHighLevelClient client, QueryBuilder queryBuilder, String index) {

        CountRequest countRequest = new CountRequest(index);

        countRequest.query(queryBuilder);

        try {
            CountResponse countResponse = client.count(countRequest, RequestOptions.DEFAULT);

            long count = countResponse.getCount();

            return count;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return 0L;
    }

    public static void main(String[] args) {

        TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("citycomple", "广州市");

        RestHighLevelClient restHighLevelClient = ESXpackRestHighLevelClient.getRestHighLevelClient();

        long l = System.currentTimeMillis();
        System.out.println("总量：" + countAPI(restHighLevelClient, termQueryBuilder, "address_base")
                + "响应时长：(ms)" + (System.currentTimeMillis() - l));

        ESXpackRestHighLevelClient.closeRestHighLevelClient();


    }
}
